package com.zxm.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxm.edu.dao.CategoryDao;
import com.zxm.edu.dao.CourseDao;
import com.zxm.edu.dto.CourseDTO;
import com.zxm.edu.entity.Category;
import com.zxm.edu.entity.Course;
import com.zxm.edu.service.CourseService;
import com.zxm.edu.util.BeanCopyUtils;
import com.zxm.edu.util.PageUtils;
import com.zxm.edu.vo.ConditionVO;
import com.zxm.edu.vo.CourseVO;
import com.zxm.edu.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;


/**
 * 课程服务
 *
 * @author silencezheng
 * @date 2022/08/10
 */
@Service
@Slf4j
public class CourseServiceImpl extends ServiceImpl<CourseDao, Course> implements CourseService {
	@Autowired
	private CourseDao courseDao;
	@Autowired
	private CategoryDao categoryDao;

	@Override
	public PageResult<CourseDTO> listCourses(ConditionVO condition) {
		// 查询总量
		Integer count = courseDao.getCount(condition);
		if (count <= 0) {
			return new PageResult<>();
		}
		// 查询后台课程列表
		List<CourseDTO> courseDTOList = courseDao.listCourses(PageUtils.getLimitCurrent(), PageUtils.getSize(), condition);
		return new PageResult<>(courseDTOList, count);
	}

	@Override
	public void deleteCourses(List<Integer> courseIdList) {
		courseDao.deleteBatchIds(courseIdList);
	}

	@Override
	@Transactional
	public void saveOrUpdateCourse(CourseVO courseVO) {
		// 保存课程分类
		Category category = saveCourseCategory(courseVO);
		// 保存或修改课程
		Course course = BeanCopyUtils.copyObject(courseVO, Course.class);
		if (Objects.nonNull(category)) {
			course.setCategoryId(category.getId());
		}
		this.saveOrUpdate(course);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Course listCourseById(Integer id) {
		return courseDao.selectById(id);
	}

	/**
	 * 保存课程分类
	 *
	 * @param courseVO 课程信息
	 * @return {@link Category} 课程分类
	 */
	private Category saveCourseCategory(CourseVO courseVO) {
		// 判断分类是否存在
		Category category = categoryDao.selectOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName, courseVO.getCategoryName()));
		if (Objects.isNull(category)) {
			category = Category.builder().categoryName(courseVO.getCategoryName()).build();
			category.setType("1");
			categoryDao.insert(category);
		}
		return category;
	}
}
